<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Auth extends Controller_Admin {

    public function before() {
        parent::before();
        $this->setLayout('login');
    }

    public function action_login() {
        $a_js = array('jquery.uniform', 'jquery.validate', 'unicorn.login');
        $this->add_js($a_js);
        $a_css = array('unicorn.login');
        $this->add_css($a_css);
        $logout = Arr::get($_GET, 'logout');
        if ((int) $logout == 1) {
            //sessin user
            $o_entity_user = Controller_Helper_Authentication::get_session();
            if ($o_entity_user instanceof Domain_Entities_User) {
                if ($o_entity_user->getId() > 0) {
                    $s_su = new Model_Service_Session_User();
                    $s_su->delete_by_user($o_entity_user->getId());
                    //DELETE cache
                    $cache = Cache::instance();

                    $cache->delete(Controller_Helper_Constant::CACHE_ADMIN_PERMISSION_USER . $o_entity_user->getId());
                    //$cache->delete(Controller_Helper_Constant::CACHE_ADMIN_PERMISSION);
                    $s_activity_user_log = new Model_Service_Activity_User_Log();
                    $s_activity_user_log->add_log(Model_Service_Activity_User_Log::ACTION_USER_LOOUT, "", $o_entity_user->getId());
                }
            }
            //clear session
            Controller_Helper_Authentication::clear_session();
            if (!empty($this->_redirect)) {
                $this->redirect($this->_redirect);
            }
        }

        $o_message = Controller_Helper_Message::get_instance();
        $a_error = $o_message->get_error();
        $a_success = $o_message->get_success();
        $o_message->reset();
        $this->template->content = View::factory("admin/auth/login")
                ->set('a_error', $a_error)
                ->set('a_success', $a_success);
    }

    public function action_logined() {

        $s_user = new Model_Service_User;
        $s_username = trim(Arr::get($_POST, 'username'));
        $s_password = trim(Arr::get($_POST, 'password'));
        $act = trim(Arr::get($_REQUEST, 'act'));
        $s_error = $s_user->validate_login($s_username, $s_password, $act, $this->getLanguage() . '/admin/login/error');
        $o_message = Controller_Helper_Message::get_instance();
        $o_message->reset();

        if ($act == 'admin') {
            $redirect = URL::base() . 'admin/auth/login';
        } else {
            $redirect = $this->_redirect;
        }

        if (!empty($s_error)) {
            $o_message->set_error($s_error);
            $this->redirect($redirect);
        } else {
            //load user
            $o_user = $s_user->get_by_username($s_username);
            $o_entity_user = $o_user->get_data();

            if (empty($o_user) || $o_entity_user->getId() <= 0) {
                $this->redirect($redirect);
            }

            $s_su = new Model_Service_Session_User();
            //insert
            $o_su = $s_su->get_by_user_id($o_entity_user->getId());
            $o_entity_su = $o_su->get_data();
            $o_entity_su->setSession_key(Security::token(true));
            $o_entity_su->setUser_Id($o_entity_user->getId());
            $o_config = Kohana::$config->load('config');

            $expired_time = $o_config->expired_time;

            $date = strtotime(date("Y-m-d H:i:s"));
            $expired = date("Y-m-d H:i:s", strtotime("+$expired_time minutes"));

            $o_entity_su->setExpired($expired);
            $o_entity_su->setType('DESKTOP');
            if ($o_entity_su->getId() > 0) {
                $o_entity_su->setModified(date("Y-m-d"));
                $s_su->update($o_entity_su);
            } else {
                $o_entity_su->setCreated(date("Y-m-d"));
                $s_su->insert($o_entity_su);
            }

            $o_entity_user_session = $o_entity_user;
            $o_entity_user_session->set_group(null);
            $o_entity_user_session->set_usergroup(null);
            $o_entity_user_session->set_permission(null);
            $o_entity_user_session->set_userpermission(null);
            $o_entity_user_session->set_sessionuser(null);

            Controller_Helper_Authentication::set_session($o_entity_user_session);

            if (trim($act) != 'admin') {
                $url = URL::base();
                if (!empty($this->_redirect)) {
                    $url = $this->_redirect;
                }
                $this->redirect($url);
                die;
            }

            if ($o_entity_user_session->getoutsideaccess() == 1) {
                //get permission
                $a_permission_user = $s_user->get_permission_for_cache($o_entity_user->getId());
                //save cache
                $cache = Cache::instance();
                $cache->set(Controller_Helper_Constant::CACHE_ADMIN_PERMISSION_USER . $o_entity_user->getId(), $a_permission_user);
                $s_per = new Model_Service_Permission();
                $a_permission = $s_per->get_permission_for_cache();
                $cache->set(Controller_Helper_Constant::CACHE_ADMIN_PERMISSION, $a_permission);
                // write log login for user
                // write log
                $s_activity_user_log = new Model_Service_Activity_User_Log();
                $s_activity_user_log->add_log(Model_Service_Activity_User_Log::ACTION_USER_LOGIN, "", $o_entity_user->getId());
            }

            if ($act == 'admin') {
                $this->redirect(URL::base() . 'admin/home/index');
            } else {
                $this->redirect($redirect);
            }
        }
        die;
    }


    public function action_forgetpassword() {
        $data = array('error' => 0, 'msg' => '');
        header('Content-type: application/json');

        $s_user = new Model_Service_User();

        $en_user = $s_user->get_by_username(Arr::get($_REQUEST, 'username'))->get_data();
        if ($en_user->getId() <= 0) {
            $data['error'] = 1;
            $data['msg'] = 'Username is not exsting.';
        } else {
            $password = rand(100000, 999999);
            $en_user->setPassword($password);
            $s_user->update($en_user);

            $config = Kohana::$config->load('email');
            $email = new Email();
            $email->from($config->REQUEST_MAIL);
            $email->to($en_user->getEmail());
            $email->subject("Reset Password");
            $email->message('New password: ' . $password, 'text/html');
            $email->send();
            $data['msg'] = $en_user->getEmail();
        }

        echo json_encode($data);
        die;
    }

}

?>
